﻿var widgetAPI = new Common.API.Widget();
var tvKey = new Common.API.TVKeyValue();

var serviioStateMachine;
var playerStateMachine;
var jobs = [];
var selectorLevel = 0;
var animationMap = {};
var hidden = {};
var Main =
        {
            elementIds: ["ipAddress", "port", "password"],
            nextIds: ["port", "password", "anchor"],
            inputs: [null, null, null],
            ready: [false, false, false]
        };

var Input = function(id, nextId)
{

    var imeReady = function(imeObject) {
        Main.ready(id);
        installFocusKeyCallbacks(imeObject);

    };
    var ime = new IMEShell(id, imeReady, 'en');
    var next = document.getElementById(nextId);
    var installFocusKeyCallbacks = function(imeObject) {
        next = document.getElementById(nextId);
        if (nextId === 'anchor')
        {
            imeObject.setKeyFunc(29460, function(keyCode) {
                alert("setting focus to " + next);
                Main.tryServer();
                next.focus();
                return false;
            });

            imeObject.setKeyFunc(29461, function(keyCode) {
                alert("setting focus to " + next);
                Main.tryServer();
                next.focus();
                return false;
            });

            imeObject.setKeyFunc(88, function(keyCode) {
                alert("setting focus to " + next);
                Main.tryServer();
                next.focus();
                return false;
            });

            imeObject.setKeyFunc(45, function(keyCode) {
                alert("setting focus to " + next);
                Main.tryServer();
                widgetAPI.sendExitEvent();
                return false;
            });
            imeObject.setKeypadPos(810, 80);
        }
        else
        {
            imeObject.setKeyFunc(29460, function(keyCode) {
                alert("setting focus to " + next);
                next.focus();
                return false;
            });

            imeObject.setKeyFunc(29461, function(keyCode) {
                alert("setting focus to " + next);
                next.focus();
                return false;
            });

            imeObject.setKeyFunc(88, function(keyCode) {
                alert("setting focus to " + next);
                next.focus();
                return false;
            });

            imeObject.setKeyFunc(45, function(keyCode) {
                alert("setting focus to " + next);
                widgetAPI.sendExitEvent();
                return false;
            });
            imeObject.setKeypadPos(810, 80);


        }
    };
};

Main.ready = function(id) {
    var ready = true,
            i;
    for (i in Main.elementIds) {
        if (Main.elementIds[i] == id) {
            Main.ready[i] = true;
        }

        if (Main.ready[i] == false) {
            ready = false;
        }
    }
};

Main.onLoad = function()
{
    alert("starting");
    $.noConflict();
    // To enable the key event processing
    document.getElementById("anchor").focus();
    // register ime input fields

    var pluginAPI = new Common.API.Plugin();
    pluginAPI.registIMEKey();
    this.createInputObjects();
    // Set Default key handler function
    widgetAPI.sendReadyEvent();
    var tvmw = document.getElementById("pluginTVMW");
    var player = document.getElementById("pluginPlayer");
    alert("starting all started 1");
    this.playerStateMachine = new PlayerStateMachine(player, tvmw);
    alert("starting all started 2");
    this.serviioStateMachine = new ServiioStateMachine(new FileApi());
    alert("starting all started 3");
    this.serviioStateMachine.onchangestate = function() {
        Main.onServiioStateChange();
    };
    this.playerStateMachine.startup();
    alert("starting all started 4");
    this.serviioStateMachine.startup();
    alert("starting all started 5");

    hidden.display = "none";
    animationMap["#search"] = {};
    animationMap["#search"]["offscreen"] = {left: "1380px"};
    animationMap["#search"]["onscreen"] = {left: "600px"};
    animationMap["#playlist"] = {};
    animationMap["#playlist"]["offscreen"] = {right: "-10px"};
    animationMap["#playlist"]["onscreen"] = {right: "200px"};
    animationMap["#serversetup"] = {};
    animationMap["#serversetup"]["offscreen"] = {top: "-720px"};
    animationMap["#serversetup"]["onscreen"] = {top: "0px"};
};

Main.createInputObjects = function()
{
    for (index in this.elementIds)
    {
        Main.inputs[index] = new Input(this.elementIds[index],
                this.nextIds[index]);
    }
};

Main.onUnload = function()
{
    this.playerStateMachine.exit();
};

Main.MainKeyHandler = function()
{
    var KeyCode = event.keyCode;
    alert("key pressed :" + KeyCode);
    switch (KeyCode)
    {
        case tvKey.KEY_LEFT :
            this.serviioStateMachine.left();
            break;
        case tvKey.KEY_RIGHT :
            this.serviioStateMachine.right();
            break;
        case tvKey.KEY_UP :
            this.serviioStateMachine.up();
            break;
        case tvKey.KEY_DOWN :
            this.serviioStateMachine.down();
            break;
        case tvKey.ENTER :
            this.serviioStateMachine.select();
            break;
        case tvKey.INFO :
            this.serviioStateMachine.info();
            break;
        case tvKey.KEY_PLAY:
            this.playerStateMachine.play();
            break;
        case tvKey.KEY_PAUSE:
            this.playerStateMachine.pause();
            break;
        case tvKey.KEY_FF:
            this.playerStateMachine.speedUp();
            break;
        case tvKey.KEY_RW:
            this.playerStateMachine.speedDown();
            break;
        case tvKey.KEY_STOP:
            this.playerStateMachine.stop();
            break;
        case tvKey.KEY_MENU:
            Main.toggleContent();
            break;
        case tvKey.KEY_EXIT:
            this.playerStateMachine.exit();
            this.serviioStateMachine.stop();
        default :
            break;
    }
};

Main.tryServer = function()
{
    var server = document.getElementById("ipAddress").value + ":" + document.getElementById("port").value;
    var password = document.getElementById("password").value;
    alert("trying server " + server + " password :" + password);
    this.serviioStateMachine.setDetails([server, password]);
};

Main.onServiioStateChange = function()
{
    var currentState = this.serviioStateMachine.current;
    alert("serviio state " + currentState);
    switch (currentState)
    {
        case "noDetails":
            Main.hide("#playlist");
            Main.hide("#search");
            Main.show("#serversetup");
            break;
        case "working":
            Main.hide("#playlist");
            Main.hide("#search");
            Main.hide("#serversetup");
            if (this.playerStateMachine.current === 'waiting')
            {
                // there is nothign to play... fire a search event off..
                this.serviioStateMachine.startContentSearch();
            }
            break;
        case "breadcrumbWaitingOnResult":
            break;
        case "breadcrumbSelect":
            Main.show("#search");
            var currentIndex = this.serviioStateMachine.selectionIndex;
            var divsToFade = jQuery('#breadcumbItem').filter(function() {
                alert("fading "+this.id);
            }).get();
            alert('fading divs' + divsToFade);
            if (divsToFade.length > 0)
            {
                alert('creating breadcrumb a');
                jQuery(divsToFade).fadeOut("slow", function() {
                    alert('creating breadcrumb a');
                    this.createBreadcrumbItem();
                });
            }
            else
            {
                alert('creating breadcrumb b');
                this.createBreadcrumbItem();
            }
            break;
        case "initialContentSearch":
        case "selectContent":
        default:
            break;
    }
    ;
};

Main.show = function(element)
{
    var option = animationMap[element]["offscreen"];
    option.display = "block";
    var to = animationMap[element]["onscreen"];
    to.display = "block";

    if (!jQuery(element).is(":visible"))
    {
        jQuery(element).css(option);
        jQuery(element).animate(to, 1000);
    }
};

Main.hide = function(element)
{
    var option = animationMap[element]["onscreen"];
    option.display = "block";
    var to = animationMap[element]["offscreen"];

    if (!jQuery(element).is(":visible"))
    {
        jQuery(element).css(option);
        jQuery(element).animate(to, 1000, function() {
            jQuery(element).css(hidden);
        });
    }
};

Main.reset = function()
{
    var fileSys = new FileSystem();
    if (fileSys.isValidCommonPath(curWidget.id))
    {
        fileSys.deleteCommonDir(curWidget.id);
    }
};

Main.createBreadcrumbItem = function()
{
    var div = document.getElementById('breadcrumb');
    var oldElement = div.firstChild;
    var ul = document.createElement('ul');
    alert('building beadcrumb');
    var selectionIndex = this.serviioStateMachine.selectionIndex;
    alert("selectionIndex " + selectionIndex);
    for (var index = 0; index <= selectionIndex; index++)
    {
        alert("built li " + index);
        var liContainer = document.createElement('li');
        alert("built li-0");
        if (index === selectionIndex)
        {
            liContainer.setAttribute('class', 'breadcrumb-selected');
        }
        alert("built li-0");
        liContainer.setAttribute('id', 'breadcrumbItem' + index);
        alert("built li-added attr");
        folderIndex = this.serviioStateMachine.breadcrumb[index].selectionIndex;
        alert("folderIndex " + folderIndex);
        alert("title " + this.serviioStateMachine.breadcrumb[index].options[folderIndex].title);
        var textNode = document.createTextNode(this.serviioStateMachine.breadcrumb[index].options[folderIndex].title);
        alert('built search item' + this.serviioStateMachine.breadcrumb[index].options[folderIndex].title);
        liContainer.appendChild(textNode);
        alert("post adding text Node");
        ul.appendChild(liContainer);
        alert("finished li");
    }
    alert("replace child function");
    div.replaceChild(ul, oldElement);
    alert('built beadcrumb');
};

